import React from 'react'
import { UdTable, UdFilter, columnRenders, http, UdDrawer, UdModal, UdPageHeader } from '@/lib'
import apis from '@/apis/AboutQuota'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import { message, Tabs , Select } from 'antd'
import InventoryModal from './component/InventoryModal'
import StockCheckModal from '../QuatoDetail/StockCheckModal'
import StockCheckModalDistributor from '../QuatoDetail/StockCheckModalDistributor'
const { TabPane } = Tabs
const { Option } = Select

export default class ImportRecordModal extends React.Component<any> {
  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private brandList: any[] = this.props.brandList //品牌公司
  private userInfo = JSON.parse(sessionStorage.getItem('UaaSysInfo')).profile
  private userId = this.userInfo.id
  private TypeList: any[] = [{
      acctType: '1',
      name: '经销商'
  }, {
      acctType: '2',
      name: '分销商'
  }]

  state: { [key: string]: any } = {
    shortBrandNameList: [],
    brandCode: '',
    dataSource: [],
    page: 1,
    size: 10,
    total: 0,
    loading: false,
    conditions: [
      {
        label: '客户名称',
        id: 'dealerName',
      },
      {
        label: '客户类型',
        id: 'agentType',
        initialValue:'1',
        render: () => (
            <Select  placeholder="请选择客户类型" >
                {
                    this.TypeList.length > 0 &&
                    this.TypeList.map(({ acctType, name }) => {
                        return <Option key={acctType} value={acctType}>{name}</Option>
                    })
                }
            </Select>
        ),
      },
    ],
  }
  columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '50px',
      render: (text, reoled, index) => index + 1,
    },
    { title: '客户编码', dataIndex: 'dealerCode', key: 'dealerCode', minWidth: '140px' },
    { title: '客户名称', dataIndex: 'dealerName', key: 'dealerName', minWidth: '180px' },
    {
      title: '销售组织',
      dataIndex: 'brandName',
      key: 'brandName',
      minWidth: '150px',
    },
    {
      title: '客户类型',
      dataIndex: 'agentType',
      key: 'agentType',
      minWidth: '150px',
      render: (text, reoled, index) => this.TypeList.find(e=>e.acctType==reoled.agentType).name,
    },
    { title: '上级经销商', dataIndex: 'parentName', key: 'parentName', minWidth: '100px' },
    { title: '最后盘点周期', dataIndex: 'description', key: 'description', minWidth: '100px' },
    { title: '最后盘点时间', dataIndex: 'createTime', key: 'createTime', minWidth: '180px' },
    { title: '最后操作人', dataIndex: 'createName', key: 'createName', minWidth: '100px' },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right' as 'right',
      width: 160,
      render: columnRenders.operate([
        {
          title: '库存盘点',
          action: (text: any, record: any) => this.showImportRecordDetailModal(record),
          show: (text: any, record: any, index: number) => record.openCheckStock !== 'N',
        },
      ]),
    },
  ]

  render() {
    let { shortBrandNameList, brandCode } = this.state
    return (
      <>
        <UdPageHeader title="库存盘点" />
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={this.state.conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={this.state.loading}
          resetAfter={this.resetFilterHandle}
        />
        <Tabs onChange={this.handChangeTabKey} type="card" defaultActiveKey={brandCode}>
          {shortBrandNameList.map(item => (
            <TabPane tab={item.title} key={item.value}></TabPane>
          ))}
        </Tabs>
        <UdTable
          rowKey="id"
          loading={this.state.loading}
          columns={this.columns}
          dataSource={this.state.dataSource}
          onChange={this.handleChangePage}
          scroll={{ x: true }}
          pagination={{
            current: this.state.page,
            pageSize: this.state.size,
            total: this.state.total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </>
    )
  }

  public componentDidMount() {
    this.getBrandCompanyList()
  }

  private handChangeTabKey = (key: string) => {
    this.setState({ brandCode: key }, () => {
      this.getRecordTableData()
    })
  }

  private getBrandCompanyList = () => {
    http.get(apis.getUserBrands).then(res => {
      const brandCompanies = res.data.map(({ brandCode: value, brandNameShort: title }) => ({ value, title }))
      const hideArr = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
      let brandfilter = brandCompanies.filter(item => hideArr.indexOf(item.title) === -1)
      this.setState({ shortBrandNameList: brandfilter, brandCode: brandfilter?.[0]?.value }, () => {
        this.getRecordTableData()
      })
    })
  }

  private showImportRecordDetailModal = (record: any): void => {
    let {brandCode} = this.state
    http.get(apis.GetInventoryDateByBrandCode, { params: { dealerCode:  record.parentCode ? record.parentCode : record.dealerCode } }).then(res => {
    // http.get(apis.GetInventoryDateByBrandCode, { params: { dealerCode: Object.is(record.brandType, '2') && record.parentCode ? record.parentCode : record.dealerCode } }).then(res => {
      let brandLists = res.data
      //* 只显示当前品牌公司的数据
      brandLists = brandLists.filter(item=>item.brandCode===brandCode)
      let canOpen = brandLists.every(item => {
        return item.isAllowd === true
      })
      let inventoryBegineTime = brandLists[0]?.inventoryDateMonths[0]?.monthStartTime
      let inventoryEndTime = brandLists[0]?.inventoryDateMonths[0]?.monthEndTime
      if (canOpen) {
        UdModal.open({
          title: '选择在盘点时间范围内的公司',
          width: '45%',
          content: <InventoryModal brandList={brandLists} />,
          onOk: value => {
            Array.isArray(value) &&
              value.length > 0 &&
              this.handStockCheck({
                value: value[0],
                record,
                inventoryBegineTime,
                inventoryEndTime,
              })
          },
        })
      } else {
        message.warn('未到盘点时间')
      }
    })
  }

  private handStockCheck = ({
    record,
    inventoryBegineTime,
    inventoryEndTime,
    value: { cycleText, brandName, brandCode },
  }) => {
    let {agentType} =this.filterForm.getFieldsValue();
    if(Object.is(record.agentType, 2) && record.parentCode){
      // 分销商库存盘点
      UdDrawer.open({
        title: `库存盘点`,
        width: '70%',
        content: (
          <StockCheckModalDistributor
            detailDataSource={{
              record,
              agentType,
              cycleText,
              brandName,
              brandCode,
              dealerName: record.dealerName,
              dealerCode: record.dealerCode,
              inventoryBegineTime,
              inventoryEndTime,
            }}
          />
        ),
      })
    }else{
      UdDrawer.open({
        title: `库存盘点`,
        width: '70%',
        content: (
          <StockCheckModal
            detailDataSource={{
              cycleText,
              agentType,
              brandName,
              brandCode,
              dealerName: record.dealerName,
              dealerCode: record.dealerCode,
              inventoryBegineTime,
              inventoryEndTime,
            }}
          />
        ),
      })
    }
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getRecordTableData()
    })
  }

  private handleSearch = (values: object) => {
    this.setState({ dataSource: [], page: 1, total: 0 }, () => {
      this.getRecordTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState({ dataSource: [], page: 1, total: 0 }, () => {
      this.getRecordTableData()
    })
  }

  private getRecordTableData = async () => {
    this.setState({ loading: true })
    let { brandCode, shortBrandNameList } = this.state
    try {
      let list: any = await http.post(apis.GetDealerCheckStock, {
        page: this.state.page,
        size: this.state.size,
        conditions: { brandCode, userId: this.userId, ...this.filterForm.getFieldsValue() },
      })
      const dataSource = list.data?.content
      let checkedBrandName: any = shortBrandNameList.filter(item => {
        return item.value === brandCode
      })?.[0]?.title
      for (let record of dataSource) {
        record.brandName = checkedBrandName
      }
      this.setState({
        dataSource,
        total: list.data.totalElements,
        loading: false,
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }
}
